<template>
  <el-card shadow="hover" :body-style="{ padding: '0' }" class="post-card" @click="handleClick">
    <div class="card-content">
      <!-- 头部区域 -->
      <div class="card-header">
        <div class="header-left">
          <el-avatar :size="34" :src="authorAvatar" />
          <div class="author-info">
            <span class="author-name">{{ username }}</span>
            <span class="post-time">{{ formattedTime }}</span>
          </div>
        </div>
        <el-tag type="info">原创</el-tag>
      </div>

      <!-- 主要内容 -->
      <div class="main-content">
        <h3 class="title">{{ title }}</h3>

        <!-- 显示第一个文本块 -->
        <p v-if="truncatedText" class="content">{{ truncatedText }}</p>
        <!-- 显示第一个图片块 -->
        <div v-if="firstImageBlock" class="image-wrapper">
          <el-image :src="firstImageBlock.url" fit="cover" class="post-image">
            <template #error>
              <div class="image-error">
                <el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="card-footer">
        <div class="tag-group">
          <el-tag class="tag" type="info" effect="plain" size="small">
            浏览 {{ view_count }}
          </el-tag>
          <el-tag class="tag" type="info" effect="plain" size="small">
            点赞 {{ like_count }}
          </el-tag>
        </div>

        <div class="action-buttons">
          <el-button v-if="my_posts" type="danger" text plain @click.stop="handleDelete">
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
          <el-button text plain>
            <el-icon>
              <ChatDotRound />
            </el-icon>
            <!-- {{ commentCount }} -->
          </el-button>
        </div>
      </div>
    </div>
  </el-card>
</template>


<script lang="ts" setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElCard, ElTag, ElImage, ElAvatar, ElButton, ElIcon, ElMessage, ElMessageBox } from 'element-plus'
import { Picture, ChatDotRound, Delete } from '@element-plus/icons-vue'
import { postsAPI } from '@/api/posts'

const props = defineProps({
  postId: {
    type: Number,
    required: true
  },
  title: {
    type: String,
    default: '测试标题'
  },
  view_count: {
    type: Number,
    default: 0
  },
  like_count: {
    type: Number,
    default: 0
  },
  created_at: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  },
  content: {
    type: Object,
    default: () => ({
      blocks: [],
      version: '1.0'
    })
  },
  my_posts: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['delete-success'])
const router = useRouter()

// 计算第一个文本块内容
const firstTextBlock = computed(() =>
  props.content.blocks.find(b => b.type === 'text')
)

// 计算第一个图片块
const firstImageBlock = computed(() =>
  props.content.blocks.find(b => b.type === 'image')
)

// 文本截断处理
const truncatedText = computed(() => {
  if (!firstTextBlock.value) return ''
  const text = firstTextBlock.value.data || ''
  return text.length > 80 ? `${text.slice(0, 80)}...` : text
})

// 格式化时间显示
const formattedTime = computed(() => {
  const date = new Date(props.created_at)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
})

// 作者头像（暂时使用默认）
const authorAvatar = computed(() =>
  'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
)

const handleClick = () => {
  router.push({
    name: 'post',
    params: { id: props.postId }
  })
}

const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要永久删除该帖子吗？此操作不可恢复！', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
      customClass: 'delete-confirm-box'
    })

    // 调用删除接口
    await postsAPI.deletePost(props.postId)

    ElMessage.success('删除成功')
    // 触发删除成功事件
    emit('delete-success', props.postId)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.message || '服务器错误'))
    }
  }
}
</script>
<style scoped>
.post-card {
  max-width: 800px;
  margin: 0 auto;
  transition: transform 0.2s;
}

.post-card:hover {
  transform: translateY(-3px);
}

.card-content {
  padding: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  font-size: 14px;
}

.post-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.main-content {
  margin-bottom: 16px;
}

.title {
  margin: 0 0 12px 0;
  font-size: 18px;
  line-height: 1.4;
  color: var(--el-text-color-primary);
}

.image-wrapper {
  margin-bottom: 16px;
  border-radius: 6px;
  overflow: hidden;
}

.post-image {
  width: 100%;
  height: 320px;
  transition: transform 0.3s;
}

.post-image:hover {
  transform: scale(1.02);
}

.content {
  font-size: 14px;
  color: var(--el-text-color-regular);
  line-height: 1.6;
  margin: 12px 0;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color);
}

.tag-group {
  display: flex;
  gap: 8px;
}

.action-buttons {
  display: flex;
  gap: 16px;

  .el-button {
    padding: 8px;
    color: var(--el-text-color-secondary);

    &:hover {
      color: var(--el-color-primary);
      background: var(--el-color-primary-light-9);
    }
  }
}

.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 200px;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-placeholder);
  font-size: 24px;
}

/* 新增删除按钮样式 */
.action-buttons .el-button.el-button--danger {
  color: var(--el-color-danger);

  &:hover {
    color: var(--el-color-danger);
    background: var(--el-color-danger-light-9);
  }
}

/* 自定义确认框样式 */
:global(.delete-confirm-box) {
  .el-message-box__headerbtn {
    display: none;
  }

  .el-message-box__content {
    padding: 20px;
  }

  .el-message-box__btns {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button:first-child {
      order: 2;
      background-color: var(--el-color-danger);
      border-color: var(--el-color-danger);
      color: white;
    }
  }
}
</style>